<template>
  <div class="profile">
    <!-- 页面标题 -->
    <div class="profile-header">
      <h1 class="page-title">个人中心</h1>
      <p class="page-description">查看和修改个人信息</p>
    </div>

    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8" :xs="24" :sm="24" :md="8">
        <el-card class="profile-card">
          <div class="profile-info">
            <!-- 头像 -->
            <div class="avatar-section">
              <el-avatar :size="100" :src="userInfo?.avatar || defaultAvatar" />
              <el-button type="text" @click="showAvatarUpload = true" class="avatar-btn">
                <el-icon><Camera /></el-icon>
                更换头像
              </el-button>
            </div>

            <!-- 基本信息 -->
            <div class="basic-info">
              <h3 class="username">{{ userInfo?.nickName || userInfo?.userName }}</h3>
              <p class="dept-info">{{ userInfo?.deptName || '暂未分配部门' }}</p>
              
              <!-- 角色标签 -->
              <div class="roles-section">
                <span class="roles-label">角色：</span>
                <el-tag
                  v-for="role in roles"
                  :key="role"
                  size="small"
                  type="primary"
                  class="role-tag"
                >
                  {{ role }}
                </el-tag>
              </div>

              <!-- 登录信息 -->
              <div class="login-info">
                <div class="info-item">
                  <span class="label">上次登录：</span>
                  <span class="value">{{ userInfo?.loginDate }}</span>
                </div>
                <div class="info-item">
                  <span class="label">登录IP：</span>
                  <span class="value">{{ userInfo?.loginIp }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 详细信息 -->
      <el-col :span="16" :xs="24" :sm="24" :md="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>详细信息</span>
              <el-button type="primary" @click="showEditDialog = true">
                <el-icon><Edit /></el-icon>
                编辑信息
              </el-button>
            </div>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">
              {{ userInfo?.userName }}
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              {{ userInfo?.nickName }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userInfo?.email || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ userInfo?.phonenumber || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ getSexText(userInfo?.sex) }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="userInfo?.status === '0' ? 'success' : 'danger'">
                {{ userInfo?.status === '0' ? '正常' : '停用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ userInfo?.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ userInfo?.updateTime }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ userInfo?.remark || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 修改密码 -->
        <el-card style="margin-top: 20px">
          <template #header>
            <span>安全设置</span>
          </template>
          
          <div class="security-section">
            <div class="security-item">
              <div class="security-info">
                <h4>登录密码</h4>
                <p>安全性高的密码可以使账号更安全</p>
              </div>
              <el-button type="primary" @click="showPasswordDialog = true">
                修改密码
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑信息对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人信息"
      width="500px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="editForm.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="editForm.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">未知</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :before-close="handleClosePassword"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordFormRules"
        label-width="80px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="上传头像"
      width="400px"
    >
      <el-upload
        class="avatar-uploader"
        action="/api/system/user/avatar"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="uploadAvatar" :src="uploadAvatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="upload-tips">
        <p>只能上传jpg/png文件，且不超过2MB</p>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAvatarUpload = false">取消</el-button>
          <el-button type="primary" @click="handleAvatarSubmit" :loading="avatarLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { getToken } from '@/utils/auth'
import type { UpdateProfileForm, ChangePasswordForm } from '@/types/user'
import defaultAvatar from '@/assets/images/profile.jpg'

const userStore = useUserStore()

// 计算属性
const userInfo = computed(() => userStore.userInfo)
const roles = computed(() => userStore.roles)

// 对话框显示状态
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const showAvatarUpload = ref(false)

// 加载状态
const editLoading = ref(false)
const passwordLoading = ref(false)
const avatarLoading = ref(false)

// 表单引用
const editFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 编辑个人信息表单
const editForm = reactive<UpdateProfileForm>({
  nickName: '',
  email: '',
  phonenumber: '',
  sex: '2',
})

// 修改密码表单
const passwordForm = reactive<ChangePasswordForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 头像上传
const uploadAvatar = ref('')
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${getToken()}`,
}))

// 表单验证规则
const editFormRules: FormRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 30, message: '昵称长度在 1 到 30 个字符', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phonenumber: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
}

const passwordFormRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 获取性别文本
const getSexText = (sex?: string) => {
  const sexMap: Record<string, string> = {
    '0': '男',
    '1': '女',
    '2': '未知',
  }
  return sexMap[sex || '2'] || '未知'
}

// 初始化编辑表单
const initEditForm = () => {
  if (userInfo.value) {
    editForm.nickName = userInfo.value.nickName || ''
    editForm.email = userInfo.value.email || ''
    editForm.phonenumber = userInfo.value.phonenumber || ''
    editForm.sex = userInfo.value.sex || '2'
  }
}

// 处理编辑信息
const handleEditSubmit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    editLoading.value = true

    // TODO: 调用更新个人信息接口
    // await updateProfile(editForm)
    
    // 模拟更新成功
    userStore.updateUserInfoAction(editForm)
    
    ElMessage.success('个人信息更新成功')
    showEditDialog.value = false
  } catch (error) {
    console.error('更新个人信息失败:', error)
  } finally {
    editLoading.value = false
  }
}

// 处理修改密码
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    // TODO: 调用修改密码接口
    // await changePassword(passwordForm)
    
    ElMessage.success('密码修改成功，请重新登录')
    
    // 清空表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    })
    
    showPasswordDialog.value = false
    
    // 重新登录
    setTimeout(() => {
      userStore.logoutAction()
    }, 1000)
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 处理头像上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 200) {
    uploadAvatar.value = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '头像上传失败')
  }
}

// 头像上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 确认头像上传
const handleAvatarSubmit = async () => {
  if (!uploadAvatar.value) {
    ElMessage.warning('请先上传头像')
    return
  }

  try {
    avatarLoading.value = true
    
    // TODO: 调用更新头像接口
    // await updateAvatar({ avatar: uploadAvatar.value })
    
    // 更新用户信息中的头像
    userStore.updateUserInfoAction({ avatar: uploadAvatar.value })
    
    ElMessage.success('头像更新成功')
    showAvatarUpload.value = false
  } catch (error) {
    console.error('更新头像失败:', error)
  } finally {
    avatarLoading.value = false
  }
}

// 关闭编辑对话框
const handleCloseEdit = () => {
  editFormRef.value?.resetFields()
  showEditDialog.value = false
}

// 关闭密码对话框
const handleClosePassword = () => {
  passwordFormRef.value?.resetFields()
  showPasswordDialog.value = false
}

// 初始化
onMounted(() => {
  initEditForm()
})
</script>

<style lang="scss" scoped>
.profile {
  padding: 20px;
}

.profile-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--kexilo-text-color-primary);
  margin: 0 0 8px;
}

.page-description {
  font-size: 14px;
  color: var(--kexilo-text-color-regular);
  margin: 0;
}

.profile-card {
  .profile-info {
    text-align: center;
  }
}

.avatar-section {
  margin-bottom: 24px;
  
  .avatar-btn {
    margin-top: 12px;
    font-size: 12px;
    color: var(--el-color-primary);
  }
}

.basic-info {
  .username {
    font-size: 20px;
    font-weight: 600;
    color: var(--kexilo-text-color-primary);
    margin: 0 0 8px;
  }
  
  .dept-info {
    font-size: 14px;
    color: var(--kexilo-text-color-regular);
    margin: 0 0 16px;
  }
}

.roles-section {
  margin-bottom: 20px;
  text-align: left;
  
  .roles-label {
    font-size: 14px;
    color: var(--kexilo-text-color-regular);
    margin-right: 8px;
  }
  
  .role-tag {
    margin-right: 8px;
  }
}

.login-info {
  text-align: left;
  
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
    
    .label {
      color: var(--kexilo-text-color-regular);
    }
    
    .value {
      color: var(--kexilo-text-color-primary);
      font-weight: 500;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-section {
  .security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .security-info {
    flex: 1;
    
    h4 {
      font-size: 16px;
      margin: 0 0 4px;
      color: var(--kexilo-text-color-primary);
    }
    
    p {
      font-size: 14px;
      margin: 0;
      color: var(--kexilo-text-color-regular);
    }
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tips {
  text-align: center;
  margin-top: 10px;
  
  p {
    font-size: 12px;
    color: var(--kexilo-text-color-regular);
    margin: 0;
  }
}

@media (max-width: 768px) {
  .profile {
    padding: 16px;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
}
</style>
